package cn.mineserv.video.videoordersystem.controller;

import cn.mineserv.video.videoordersystem.model.Admin;
import cn.mineserv.video.videoordersystem.model.SystemInformation;
import cn.mineserv.video.videoordersystem.model.User;
import cn.mineserv.video.videoordersystem.model.UserExample;
import cn.mineserv.video.videoordersystem.service.AdminService;
import cn.mineserv.video.videoordersystem.service.MediaService;
import cn.mineserv.video.videoordersystem.service.SystemInformationService;
import cn.mineserv.video.videoordersystem.service.UserService;
import cn.mineserv.video.videoordersystem.utils.AESDESEncryptUtil;
import cn.mineserv.video.videoordersystem.utils.CookieUtil;
import cn.mineserv.video.videoordersystem.utils.Util;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Producer;
import com.alibaba.fastjson2.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @author 爱吃蛋白的丶圆周率
 * @company 圆周率有限公司
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Value("${server.servlet.context-path}")
    private String contextPath;
    @Resource
    private UserService userService;

    @Resource
    private AdminService adminService;

    @Resource
    private MediaService mediaService;

    @Resource
    private SystemInformationService systemInformationService;

    @GetMapping("/login")
    public String login(){
        return "user/login";
    }

    @PostMapping("/login")
    public String login(Model model, String userName, String password, @RequestParam("login_checkcode") String code, HttpServletResponse response, HttpServletRequest request, @CookieValue(name = "ticket",
            defaultValue = "1234") String currentCode, HttpSession session) throws Exception {
        if(Objects.equals(currentCode, "1234")){
//            model.addAttribute("message", "验证码错误");
            return "user/login";
        }
        if(!code.equalsIgnoreCase(AESDESEncryptUtil.decryptString(currentCode, AESDESEncryptUtil.SYMMETRY_ENCRYPT.AES))){
            model.addAttribute("message", "验证码错误");
            return "user/login";
        }
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_name", userName);
        queryWrapper.eq("password", Util.md5(password));
        Admin one = adminService.getOne(queryWrapper);
        if(one != null){
            one.setPassword(null);
            session.setAttribute("userType", "admin");
            session.setAttribute("admin", one);
            return "redirect:/admin/adminIndex";
        }
        UserExample example = new UserExample();
        example.createCriteria().andUserNameEqualTo(userName).andPasswordEqualTo(Util.md5(password));
        List<User> users = userService.selectByExample(example);
        if(users.size() == 0){
            model.addAttribute("message","用户名或密码错误");
            return "user/login";
        }
        session.setAttribute("userType", "user");
        session.setAttribute("user", users.get(0));
        session.setMaxInactiveInterval(60*24*365);
//        CookieUtil.setValue(response,"user_token",users.get(0).getUserName());
        CookieUtil.removeValue(response, "token");
        return "redirect:/homepage";
    }

    @GetMapping("/logout")
    public String logout(Model model, HttpServletResponse response, HttpSession session) throws Exception {
//        CookieUtil.removeValue(response, "user");
//        CookieUtil.removeValue(response, "admin");
        session.removeAttribute("admin");
        session.removeAttribute("user");
        session.removeAttribute("userType");
        model.addAttribute("message", "退出成功");
        return "redirect:/homepage";
    }

    @GetMapping("/register")
    public String register(){
        return "user/register";
    }

    @PostMapping("/register")
    public String register(Model model, String userName, String password, String rePassword, @RequestParam("register_checkcode")  String code, HttpServletResponse response, @CookieValue(name = "ticket",
            defaultValue = "1234") String currentCode, HttpSession session) throws Exception {
        if(Objects.equals(currentCode, "1234")){
//            model.addAttribute("message", "验证码错误");
            return "user/login";
        }
        if(!code.equalsIgnoreCase(AESDESEncryptUtil.decryptString(currentCode, AESDESEncryptUtil.SYMMETRY_ENCRYPT.AES))){
            model.addAttribute("message", "验证码错误");
            return "user/register";
        }
        if(!password.equals(rePassword)){
            model.addAttribute("message", "两次密码不一致");
            return "user/register";
        }
        UserExample example = new UserExample();
        example.createCriteria().andUserNameEqualTo(userName);
        List<User> users = userService.selectByExample(example);
        if(users.size() != 0){
            model.addAttribute("message","用户名已存在");
            return "user/register";
        }
        User user = new User();
        user.setPassword(Util.md5(password));
        user.setUserName(userName);
        user.setUserStatus(0);
        user.setUserAvatar("/image/avatar/default.jpg");
        user.setNickName(userName);
        boolean save = userService.save(user);
        model.addAttribute("message", save ? "注册成功" : "注册失败");
        if(save){
            session.setAttribute("userType", "user");
            session.setAttribute("user", user);
//            CookieUtil.setValue(response,"user_token",user.getUserName());
            CookieUtil.removeValue(response, "token");
        }
        return "redirect:/homepage";
    }

    @ResponseBody
    @RequestMapping(value = "/checkUsername",method = {RequestMethod.GET,RequestMethod.POST})
    public Map<String,Object> checkUsername(String username, HttpServletResponse response) throws Exception{
        response.setContentType("text/json");
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        List<User> list = userService.list(queryWrapper);
        int size = list.size();
        List<Admin> list1 = adminService.list(new QueryWrapper<Admin>().eq("admin_name", username));
        size +=list1.size();
        boolean isExist = size > 0;
        map.put("code", isExist ? 301 : 300);
        map.put("msg", isExist ? "用户名不可用" : "用户名可用");
        map.put("isExist", isExist);
        map.put("username", username);
        return map;
    }

    @GetMapping("/info")
    public String personCenter(){
        return "user/PersonCenter";
    }

    @GetMapping("/notice")
    public String systemNotice(Model model,HttpSession session){
        List<SystemInformation> systemInformationList = systemInformationService.list(new QueryWrapper<SystemInformation>().eq("user_id", ((User) (session.getAttribute("user"))).getUserId()));
        model.addAttribute("list",systemInformationList);
        return "user/SystemNotice";
    }

    @PostMapping("/notice")
    @ResponseBody
    public String systemNotice(HttpSession session){
        JSONObject src = new JSONObject();
        src.put("code",200);
        Object userType = session.getAttribute("userType");
        if (userType != null){
            if(userType.equals("user")){
                List<SystemInformation> systemInformationList = systemInformationService.list(new QueryWrapper<SystemInformation>().eq("user_id", ((User) (session.getAttribute("user"))).getUserId()));
                src.put("data", systemInformationList);
                src.put("message", "获取成功1");
            }else {
                src.put("data", new ArrayList<SystemInformation>());
                src.put("message", "获取成功2");
            }
        }else {
            src.put("data", new ArrayList<SystemInformation>());
            src.put("message", "获取成功3");
        }
        return src.toJSONString();
    }

    @PostMapping("/notice/add")
    public void addNewSystemNotice(Integer mediaId,Integer adminId,String infoCause,Integer infoStatus,Integer infoType,HttpServletResponse response) throws Exception{
        SystemInformation systemInformation = new SystemInformation();
        systemInformation.setAdminId(adminId);
        systemInformation.setUserId(mediaService.getById(mediaId).getUserId());
        systemInformation.setInfoStatus(infoStatus);
        systemInformation.setInfoType(infoType);
        systemInformation.setInfoTime(new Date());
        if(infoType == 1){
            systemInformation.setInfoTitle("您的视频审核已通过");
            systemInformation.setInfoText("恭喜，您的视频<i class=\"bi bi-caret-right-fill\"></i><a style=\"color: #007bff\" href='"+contextPath+"/media/play?id="+mediaId+"'>"+mediaService.getById(mediaId).getMediaName()+"</a>审核通过，让更多小伙伴看看吧。");
        } else if (infoType == 2) {
            systemInformation.setInfoTitle("您的视频未审核通过");
            systemInformation.setInfoText("抱歉，由于您的视频<i class=\"bi bi-caret-right-fill\"></i><a style=\"color: #007bff\" href='"+contextPath+"/media/play?id="+mediaId+"'>"+mediaService.getById(mediaId).getMediaName()+"</a>'"+infoCause+"',未被审核通过，请更正视频内容");
        }
        boolean save = systemInformationService.save(systemInformation);
        System.out.println("addNewSystemNotice:save = " + save);
        response.sendRedirect(contextPath+"/admin/adminReview");
    }

    @GetMapping("/interact")
    public String interact(){
        return "user/Interact";
    }

}
